package show.me.the.money.util.context;

import java.util.HashMap;
import java.util.List;

import java.util.Iterator;

import show.me.the.money.accredit.Role;
import show.me.the.money.accredit.User;


@SuppressWarnings("unchecked")
public class UserContext extends Context {

	private static final long serialVersionUID = 1L;
	private User user;
	public UserContext(User user){
		super();
		this.user = user;
	}
	
	public boolean has(String name){
		return user.hasProperty(name);
	}
	
	public Object get(String name,HashMap<String,Object> arg){
		if(user == null){
			return null;
		}
		if(name.equals("userId")){
			return user.getId();
		}
		if(name.equals("userName")){
			return user.getName();
		}
		if(name.equals("instance")){
			return user;
		}
		int p = name.indexOf(".");
		if(p > -1){
			String prefix = name.substring(0,p);
			String prop = name.substring(p+1);
			if(prefix.equals("prop")){
				//prop = name.substring(p+1);
				return user.getProperty(prop);
			}
			if(prefix.equals("role")){
				List<Role> roles = user.getRoles();
				for(Iterator<Role> it =(Iterator) roles.iterator();it.hasNext();){
					Role r = it.next();
					if(r.hasProperty(prop)){
						return r.getProperty(prop);
					}
				}
			}
			if(prefix.equals("manageUnit")){
				return user.get(name);
			}
			if(prefix.equals("aliesRole")){
				return user.get(name);
			}
		}
		return null;
		
	}

}
